package com.ht.medicaltreatment.activity.haocai2

import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.gym.baselib.base.BaseActivity
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.adapter.ConsumableLeftLeftAdapter
import com.ht.medicaltreatment.adapter.ItemCaiZhiAdapter
import com.ht.medicaltreatment.adapter.ItemGGAdapter
import com.ht.medicaltreatment.adapter.ItemPPAdapter
import com.ht.medicaltreatment.adapter.ItemXHAdapter
import com.ht.medicaltreatment.adapter.SubjectRecordAdapter
import com.ht.medicaltreatment.adapter.SubjectRightAdapter
import com.ht.medicaltreatment.base.BaseUrl
import com.ht.medicaltreatment.bean.ProjectConsumableD
import com.ht.medicaltreatment.bean.SubmitConsumableJSON
import com.ht.medicaltreatment.view.InputCountDialog
import com.ht.medicaltreatment.viewmodel.ConsumableViewModel
import com.xgst.lib.utils.showToast
import kotlinx.android.synthetic.main.activity_add_subject_layout.addRecyclerView
import kotlinx.android.synthetic.main.activity_add_subject_layout.clRecord
import kotlinx.android.synthetic.main.activity_add_subject_layout.imgAdd
import kotlinx.android.synthetic.main.activity_add_subject_layout.imgDelete
import kotlinx.android.synthetic.main.activity_add_subject_layout.imgIcon
import kotlinx.android.synthetic.main.activity_add_subject_layout.recyclerViewLeft
import kotlinx.android.synthetic.main.activity_add_subject_layout.recyclerViewRight
import kotlinx.android.synthetic.main.activity_add_subject_layout.rvCZ
import kotlinx.android.synthetic.main.activity_add_subject_layout.rvGG
import kotlinx.android.synthetic.main.activity_add_subject_layout.rvPP
import kotlinx.android.synthetic.main.activity_add_subject_layout.rvXH
import kotlinx.android.synthetic.main.activity_add_subject_layout.svAdd
import kotlinx.android.synthetic.main.activity_add_subject_layout.tvAdd
import kotlinx.android.synthetic.main.activity_add_subject_layout.tvAddCount
import kotlinx.android.synthetic.main.activity_add_subject_layout.tvCancel
import kotlinx.android.synthetic.main.activity_add_subject_layout.tvCount1
import kotlinx.android.synthetic.main.activity_add_subject_layout.tvName
import kotlinx.android.synthetic.main.activity_add_subject_layout.tvName1
import kotlinx.android.synthetic.main.activity_add_subject_layout.tvProgress
import kotlinx.android.synthetic.main.activity_add_subject_layout.tvRecordTitle
import kotlinx.android.synthetic.main.activity_add_subject_layout.tvSubmit
import kotlinx.android.synthetic.main.activity_add_subject_layout.viewBg

//添加耗材
class AddSubjectActivity : BaseActivity(), OnItemChildClickListener, OnItemClickListener,
    View.OnClickListener {
    override fun getLayoutId() = R.layout.activity_add_subject_layout

    private val modle by viewModels<ConsumableViewModel>()
    private lateinit var rightAdapter: SubjectRightAdapter
    private lateinit var xhAdapter: ItemXHAdapter
    private lateinit var ggAdapter: ItemGGAdapter
    private lateinit var ppAdapter: ItemPPAdapter
    private lateinit var caizhiAdapter: ItemCaiZhiAdapter
    private lateinit var recordAdapter: SubjectRecordAdapter
    private val addList = mutableListOf<SubmitConsumableJSON.ProjectConsumableListBean>()
    val bean = SubmitConsumableJSON()
    private var sign = 0
    private var addCountList: MutableList<ProjectConsumableD>? = null
    private var xinghao = ""
    private var guige = ""
    private var pinpai = ""
    private var caizhi = ""
    private var name = ""
    private var imageUrl = ""

    private var xinghaoPosition = -1
    private var guigePosition = -1
    private var pinpaiPosition = -1
    private var caizhiPosition = -1
    private var consumableId = -1
    private var id = -1
    private var isUpdate = false

    override fun init() {
        setTitle("添加耗材")
        id = intent.getIntExtra("id", -1)
        bean.projectConsumableList = addList
        bean.projectId = id

        recyclerViewRight.layoutManager = LinearLayoutManager(this)
        rightAdapter = SubjectRightAdapter()
        recyclerViewRight.adapter = rightAdapter
        rightAdapter.setOnItemChildClickListener(this)

        recyclerViewLeft.layoutManager = LinearLayoutManager(this)
        val leftAdapter = ConsumableLeftLeftAdapter();
        recyclerViewLeft.adapter = leftAdapter
        leftAdapter.setOnItemClickListener(this)

        rvXH.layoutManager = GridLayoutManager(this, 3)
        xhAdapter = ItemXHAdapter();
        rvXH.adapter = xhAdapter
        xhAdapter.setOnItemClickListener(this)

        rvGG.layoutManager = GridLayoutManager(this, 3)
        ggAdapter = ItemGGAdapter();
        rvGG.adapter = ggAdapter
        ggAdapter.setOnItemClickListener(this)

        rvPP.layoutManager = GridLayoutManager(this, 3)
        ppAdapter = ItemPPAdapter();
        rvPP.adapter = ppAdapter
        ppAdapter.setOnItemClickListener(this)

        rvCZ.layoutManager = GridLayoutManager(this, 3)
        caizhiAdapter = ItemCaiZhiAdapter();
        rvCZ.adapter = caizhiAdapter
        caizhiAdapter.setOnItemClickListener(this)

        addRecyclerView.layoutManager = LinearLayoutManager(this)
        recordAdapter = SubjectRecordAdapter()
        addRecyclerView.adapter = recordAdapter
        recordAdapter.setOnItemChildClickListener(this)

        showProgress()
        modle.consumableList({
            dismissProgress()
            leftAdapter.setNewInstance(it)
        })

        //回显数据
        modle.init(id) {
            addCountList = it.projectConsumableList
            if (addCountList?.size!! > 0) {
                isUpdate = true
            }
            tvProgress.text = "使用进度：${it.consumableUseProgress}"
            it.projectConsumableList.forEach {
                val data = SubmitConsumableJSON.ProjectConsumableListBean()
                data.consumableId = it.consumableId
                data.number = it.number

                data.id = it.id
                data.model = it.consumable.model
                data.specification = it.consumable.specification
                data.brand = it.consumable.brand
                data.material = it.consumable.material
                data.picturePath = it.consumable.picturePath

                bean.projectConsumableList.add(data)
            }

            recordAdapter.setNewInstance(bean.projectConsumableList)
            tvAddCount.text = "已添加耗材：${bean.projectConsumableList.size}"
            tvName.text = "专题：${it.protocolNumber}"

        }

        imgDelete.setOnClickListener(this)
        imgAdd.setOnClickListener(this)
        tvAdd.setOnClickListener(this)
        tvSubmit.setOnClickListener(this)
        tvAddCount.setOnClickListener(this)
        tvCancel.setOnClickListener(this)
        tvRecordTitle.setOnClickListener(this)

    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        if (adapter is SubjectRecordAdapter) {
            val item = adapter.getItem(position)
            InputCountDialog(this, item.number).showDialog {
                val count = it.toInt()
                if(count == 0){
                    adapter.removeAt(position)
                    tvAddCount.text = "已添加耗材：${adapter.data.size}"
                }else{
                    adapter.data[position].number = it.toInt()
                    adapter.notifyItemChanged(position)
                }
            }
        } else if (adapter is SubjectRightAdapter) {
            svAdd.visibility = View.VISIBLE
            viewBg.visibility = View.VISIBLE

            tvName1.text = adapter.getItem(position)

            initParams()

            name = adapter.getItem(position)
            showProgress()
            //型号
            modle.xinghao(sign, name, {
                dismissProgress()
                xhAdapter.setNewInstance(it)
            })
        }
    }

    var checkedPosition = -1

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        //左侧列表
        if (adapter is ConsumableLeftLeftAdapter) {
            adapter.data[position].isChecked = true
            adapter.notifyItemChanged(position)
            if (checkedPosition != -1) {
                adapter.data[checkedPosition].isChecked = false
                adapter.notifyItemChanged(checkedPosition)
            }
            checkedPosition = position

            val item = adapter.getItem(position)
            imageUrl = item.url
            Glide.with(this)
                .load(BaseUrl.baseUrl()+imageUrl)
                .into(imgIcon)
            this.sign = item.sign
            showProgress()
            modle.consumableListRight(sign, {
                dismissProgress()
                rightAdapter.setUrl(imageUrl)
                rightAdapter.setNewInstance(it)
            })
        } else if (adapter is ItemXHAdapter) {
            xinghao = adapter.getItem(position)
            if (xinghaoPosition >= 0) {
                adapter.data[xinghaoPosition] = adapter.data[xinghaoPosition].split(",")[0]
                adapter.notifyItemChanged(xinghaoPosition)
            }

            adapter.data[position] = xinghao + ",X"
            adapter.notifyItemChanged(position)
            xinghaoPosition = position

            ggAdapter.setNewInstance(null)
            ppAdapter.setNewInstance(null)
            caizhiAdapter.setNewInstance(null)
            //型号 - 规格
            modle.guige(sign, name, xinghao, {
                dismissProgress()
                ggAdapter.setNewInstance(it)
            })
        } else if (adapter is ItemGGAdapter) {
            //规格 - 品牌
            guige = adapter.getItem(position).specification
            consumableId = adapter.getItem(position).id
            if (guigePosition >= 0) {
                adapter.data[guigePosition].isChecked = false
                adapter.notifyItemChanged(guigePosition)
            }

            ppAdapter.setNewInstance(null)
            caizhiAdapter.setNewInstance(null)

            adapter.data[position].isChecked = true
            adapter.notifyItemChanged(position)
            guigePosition = position

            modle.pinpai(sign, name, xinghao, guige, {
                dismissProgress()
                ppAdapter.setNewInstance(it)
            })
        } else if (adapter is ItemPPAdapter) {
            //品牌 - 材质
            pinpai = adapter.getItem(position).brand
            consumableId = adapter.getItem(position).id

            if (pinpaiPosition >= 0) {
                adapter.data[pinpaiPosition].isChecked = false
                adapter.notifyItemChanged(pinpaiPosition)
            }

            caizhiAdapter.setNewInstance(null)

            adapter.data[position].isChecked = true
            adapter.notifyItemChanged(position)
            pinpaiPosition = position

            modle.caizhi(sign, name, xinghao, guige, pinpai, {
                dismissProgress()
                caizhiAdapter.setNewInstance(it)
            })
        } else if (adapter is ItemCaiZhiAdapter) {
            caizhi = adapter.getItem(position).material
            consumableId = adapter.getItem(position).id

            if (caizhiPosition >= 0) {
                adapter.data[caizhiPosition].isChecked = false
                adapter.notifyItemChanged(caizhiPosition)
            }

            adapter.data[position].isChecked = true
            adapter.notifyItemChanged(position)
            caizhiPosition = position
        }
    }

    fun initParams() {
        xinghao = ""
        guige = ""
        pinpai = ""
        caizhi = ""
        name = ""
        //imageUrl = ""

        xinghaoPosition = -1
        guigePosition = -1
        pinpaiPosition = -1
        caizhiPosition = -1
        consumableId = -1

        xhAdapter.setNewInstance(null)
        ggAdapter.setNewInstance(null)
        ppAdapter.setNewInstance(null)
        caizhiAdapter.setNewInstance(null)

    }

    override fun onClick(v: View?) {
        when (v) {
            imgDelete -> {
                var count = tvCount1.text.toString().toInt()
                if (count > 1) {
                    tvCount1.text = "${--count}"
                }
            }

            imgAdd -> {
                var count = tvCount1.text.toString().toInt()
                tvCount1.text = "${++count}"
            }

            tvCancel -> {
                svAdd.visibility = View.GONE
                viewBg.visibility = View.GONE
            }

            //添加
            tvAdd -> {

                if(TextUtils.isEmpty(xinghao)){
                    showToast("请选择型号")
                    return
                }

                if(TextUtils.isEmpty(guige)){
                    showToast("请选择规格")
                    return
                }

                if(TextUtils.isEmpty(pinpai) && ppAdapter.data.size > 0){
                    showToast("请选择品牌")
                    return
                }

                if(TextUtils.isEmpty(caizhi) && caizhiAdapter.data.size > 0){
                    showToast("请选择材质")
                    return
                }

                svAdd.visibility = View.GONE
                viewBg.visibility = View.GONE

                val data = SubmitConsumableJSON.ProjectConsumableListBean()
                data.consumableId = consumableId
                data.number = tvCount1.text.toString().toInt()
                data.model = xinghao
                data.specification = guige
                data.brand = pinpai
                data.material = caizhi
                data.picturePath = imageUrl

                //bean.projectConsumableList.add(data)

                //var has = false
                recordAdapter.data?.forEachIndexed { index, item ->
                    if (item.consumableId == consumableId) {
                        recordAdapter.data[index].number =
                            recordAdapter.data[index].number + data.number
                        recordAdapter.notifyItemChanged(index)
                        //has = true
                        return
                    }
                }
                //if(has)return
                recordAdapter.addData(data)
                tvAddCount.text = "已添加耗材：${recordAdapter.data.size}"
            }

            //提交
            tvSubmit -> {
                bean.isUpdate(isUpdate)
                bean.projectConsumableList = recordAdapter.data
                showProgress()
                modle.submit(bean, {
                    dismissProgress()
                    showToast("提交成功")
                    finish()
                })
            }

            //查看提交记录
            tvAddCount -> {
                LogUtils.i("查看提交记录  "+recordAdapter.data.size)
                if (recordAdapter.data.size == 0) return
                if (clRecord.isVisible) {
                    clRecord.visibility = View.GONE
                } else {
                    clRecord.visibility = View.VISIBLE
                }
            }

            tvRecordTitle -> {
                clRecord.visibility = View.GONE
            }
        }
    }
}
